#include<iostream>
#include<cstdio>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

#define FILENAME "log.txt"
#define SIZE 1024

int main()
{
    //open file
    int fd = open(FILENAME, O_RDWR|O_APPEND|O_CREAT, 0666);
    if (fd < 0)
    {
        perror("open");
        return 1;
    }

    // 调整file size
    ftruncate(fd, SIZE);

    //建立映射
    /*void *mmap(void *addr, size_t length, int prot, int flags,
           int fd, off_t offset);*/
    char* mmap_addr = (char*)mmap(nullptr, SIZE, PROT_WRITE, MAP_SHARED, fd, 0);
    if (mmap_addr == MAP_FAILED)
    {
        perror("mmap");
        return 2;
    }

    //写入操作
    for (int c = 'a', i = 0; c <= 'z'; c++, i++)
    {
        mmap_addr[i] = c;
    }

    //取消映射
    munmap(mmap_addr, SIZE);

    //关闭文件
    close(fd);
    std::cout << "写入映射完毕" << std::endl;

    return 0;
}




















